<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <TopSearch
          @searchListByCommand="searchListByCommand"
          @reload="getQuestionsList"
        ></TopSearch>
        <!-- tab栏 -->
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="全部" name="all"></el-tab-pane>
          <el-tab-pane label="待审核" name="uncheck"></el-tab-pane>
          <el-tab-pane label="已审核" name="checked"></el-tab-pane>
          <el-tab-pane label="已拒绝" name="refuse"></el-tab-pane>
        </el-tabs>
        <!-- 提示框 -->
        <el-alert :title="title" type="info" show-icon> </el-alert>
        <!-- tab表格 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="number" label="试题编号" width="250">
          </el-table-column>
          <el-table-column prop="subjectID" label="学科" width="120">
          </el-table-column>
          <el-table-column prop="catalogID" label="目录" width="120">
          </el-table-column>
          <el-table-column prop="questionType" label="题型" width="120">
          </el-table-column>
          <el-table-column prop="question" label="题干" width="250">
            <template #default="{ row }">
              {{ row.question.replace(teg, "") }}
            </template>
          </el-table-column>
          <el-table-column prop="addDate" label="录入时间" width="200">
            <template #default="{ row }">
              {{ time(row.addDate, "YYYY-MM-DD HH:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="120">
          </el-table-column>
          <el-table-column prop="creator" label="录入人" width="120">
          </el-table-column>
          <el-table-column prop="chkState" label="审核状态" width="120">
          </el-table-column>
          <el-table-column prop="chkRemarks" label="审核意见" width="120">
          </el-table-column>
          <el-table-column prop="chkUser" label="审核人" width="120">
          </el-table-column>
          <el-table-column prop="publishState" label="发布状态" width="120">
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="250">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="handlePreview(row.id)"
              >
                预览
              </el-button>
              <el-button
                type="text"
                size="small"
                :disabled="row.chkState !== '待审核'"
                @click="check(row.id)"
              >
                审核
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleEdit(row.id)"
                :disabled="row.publishStateValue === 0"
              >
                修改
              </el-button>
              <el-button
                type="text"
                v-if="row.publishStateValue === 1"
                size="small"
                @click="handleOut(row, '上架', 0)"
              >
                上架
              </el-button>
              <el-button
                type="text"
                v-else
                size="small"
                @click="handleOut(row, '下架', 1)"
              >
                下架
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="deleteList(row.id)"
                :disabled="row.publishStateValue === 0"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pagesize"
           layout="prev, pager, next,sizes, jumper"
            :total="total"
             background
          >
          </el-pagination>
        </div>
      </el-card>
      <!-- 审核对话框 -->
      <QuestionsCheck
        :z-index="1000"
        :validate-on-rule-change="false"
        :checkVisible.sync="checkVisible"
        :checkId="checkId"
        @reload="getQuestionsList"
      ></QuestionsCheck>
      <!-- <el-dialog title="审核" :visible="checkVisible" @close="handleClose" width="400px">
        <el-form :model="formData" ref="form" :rules="rules" >
          <el-form-item  prop="chkState">
            <el-radio-group v-model="formData.chkState" >
              <el-radio :label="1">同意</el-radio>
              <el-radio :label="2">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="chkRemarks">
            <el-input type="textarea" placeholder="请输入审核意见" v-model="formData.chkRemarks"></el-input>
          </el-form-item>
           <el-form-item style="text-align:end">
            <el-button type="info" @click="checkVisible=false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog> -->
    </div>
    <!-- 预览对话框 -->
    <QuestionsPreview
      :showPreview.sync="showPreview"
      :previewRowData.sync="previewRowData"
      :reduceTagQuestion="reduceTagQuestion"
      :reduceTagAnswer="reduceTagAnswer"
    ></QuestionsPreview>
  </div>
</template>

<script>
import {
  choice,
  choicePublish,
  remove,
  detail as choiceDetail
} from '@/api/hmmm/questions'
import { simple } from '@/api/hmmm/subjects'
import { detail } from '@/api/hmmm/articles'
import { simple as directorysSimple } from '@/api/hmmm/directorys'
// import { difficulty, questionType, chkType } from '@/api/hmmm/constants'
import QuestionsCheck from '@/module-hmmm/components/questions-check'
import TopSearch from '@/module-hmmm/components/top-search'
import QuestionsPreview from '@/module-hmmm/components/questions-preview'
import dayjs from 'dayjs'
export default {
  name: 'QuestionsChoice',
  data () {
    return {
      // tab栏高亮名
      activeName: 'all',
      // 表格数据
      tableData: [],
      page: 1,
      pagesize: 10,
      total: 0,
      // 过滤标签的正则表达
      teg: /<[^>]+>/g,
      // 储存学科简单列表
      subjectSimleList: [],
      // 储存目录简单列表
      directorysSimpleList: [],
      // 控制审核对话框显示与隐藏
      checkVisible: false,
      // // 审核对话框数据
      // formData: {
      //   chkState: 1,
      //   chkRemarks: ''
      // },
      // // 校验规则
      // rules: {
      //   chkRemarks: [
      //     { required: true, trigger: ['blur', 'change'], message: '意见不能为空' }
      //   ]
      // },
      // 审核Id
      checkId: 0,
      // 控制预览框显示隐藏
      showPreview: false,
      // 预览的回显数据
      previewRowData: {
        code: '',
        title: '',
        img: '',
        isRight: 1
      },
      reduceTagQuestion: '', // 传过去的dialog题干
      reduceTagAnswer: '' // 传过去的dialog解析
    }
  },
  components: { QuestionsCheck, TopSearch, QuestionsPreview },
  computed: {
    title () {
      return '数据一共有' + this.total + '条'
    }
  },
  async created () {
    // 获取学科简单列表用于处理数据
    const { data } = await simple()
    // console.log(data)
    this.subjectSimleList = data
    // 获取目录简单列表用于数据处理
    const { data: data1 } = await directorysSimple()
    // console.log(data1, '123------AA')
    this.directorysSimpleList = data1
    this.getQuestionsList({
      page: this.page,
      pagesize: this.pagesize
    })
    const detail1 = await detail({ id: 29 })
    console.log(detail1)
  },
  methods: {
    // 获取精选题库列表
    async getQuestionsList (listData) {
      const { data } = await choice(listData)
      console.log(data, '123cc')
      // 处理表格数据

      this.tableData = data.items
      // console.log(this.tableData, 'this.tableData')
      this.total = data.counts
      console.log(this.dataSet(this.tableData), 'this.dataSet(this.tableData)')
      this.dataSet(this.tableData)
    },
    // tab栏点击事件
    handleClick (tab, event) {
      if (this.activeName === 'all') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize
        })
      }
      if (this.activeName === 'uncheck') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 0
        })
      }
      if (this.activeName === 'checked') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 1
        })
      }
      if (this.activeName === 'refuse') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 2
        })
      }
    },
    // 页面数量变化
    handleSizeChange (val) {
      this.pagesize = val
      // 根据不同页面发送不同请求
      if (this.activeName === 'all') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize
        })
      }
      if (this.activeName === 'uncheck') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 0
        })
      }
      if (this.activeName === 'checked') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 1
        })
      }
      if (this.activeName === 'refuse') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 2
        })
      }
    },
    // 改变当前页
    handleCurrentChange (val) {
      this.page = val
      // 根据不同页面发送不同请求
      if (this.activeName === 'all') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize
        })
      }
      if (this.activeName === 'uncheck') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 0
        })
      }
      if (this.activeName === 'checked') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 1
        })
      }
      if (this.activeName === 'refuse') {
        this.getQuestionsList({
          page: this.page,
          pagesize: this.pagesize,
          chkState: 2
        })
      }
    },
    // 时间处理函数
    time (data, str) {
      return dayjs(data).format(str)
    },
    // 渲染数据处理函数
    dataSet (data) {
      console.log(data, '13')
      data.forEach((item) => {
        item.publishStateValue = item.publishState
        for (const k in item) {
          // 处理难度
          if (k === 'difficulty') {
            // const o = difficulty.find((sum) => {
            //   return sum.value === Number(item[k])
            // })
            // item[k] = o.label ? o.label : '未知'
            // console.log(item[k], 'key')
            if (Number(item[k]) === 1) {
              item[k] = '简单'
            }
            if (Number(item[k]) === 2) {
              item[k] = '一般'
            }
            if (Number(item[k]) === 3) {
              item[k] = '困难'
            }
          }
          // 处理审核状态
          if (k === 'chkState') {
            // const o = chkType.find((sum) => {
            //   return sum.value === Number(item[k])
            // })
            // item[k] = o.label ? o.label : '未知'
            // console.log(item[k], '审核')
            if (Number(item[k]) === 0) {
              item[k] = '待审核'
            }
            if (Number(item[k]) === 1) {
              item[k] = '通过'
            }
            if (Number(item[k]) === 2) {
              item[k] = '拒绝'
            }
          }
          // 处理发布状态
          if (k === 'publishState') {
            if (Number(item[k]) === 0 && Number(item.chkState) === 1) {
              item[k] = '已发布'
            } else if (
              Number(item.chkState) === 2 ||
              Number(item.chkState) === 0
            ) {
              item[k] = '待发布'
            } else {
              item[k] = '已下架'
            }
          }
          // 处理题型
          if (k === 'questionType') {
            // const o = questionType.find((sum) => {
            //   return sum.value === Number(item[k])
            // })
            // item[k] = o.label ? o.label : '未知'
            if (Number(item[k]) === 1) {
              item[k] = '简单'
            }
            if (Number(item[k]) === 2) {
              item[k] = '一般'
            }
            if (Number(item[k]) === 3) {
              item[k] = '困难'
            }
          }
          // 处理学科数据
          if (k === 'subjectID') {
            this.subjectSimleList.forEach((item1) => {
              if (Number(item1.value) === Number(item[k])) {
                item[k] = item1.label
                // console.log(item[k], '学科')
              }
            })
          }
          // 处理学科数据
          if (k === 'catalogID') {
            this.directorysSimpleList.forEach((item2) => {
              if (item2.value.number === item[k].number) {
                item[k] = item2.label
                // console.log(item[k], '123xueke')
              }
            })
          }
        }
      })
    },

    // 点击上下架按钮
    async handleOut (row, str, publishState) {
      console.log(row)
      const id = row.id

      const str1 = '是否' + str + '该精选试题'
      this.$confirm(str1, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发送请求上下架
        await choicePublish({
          id,
          publishState
        })
        this.$message.success(str + '成功')
        this.getQuestionsList()
      })
    },
    // 点击修改按钮
    handleEdit (id) {
      this.$router.push(`/questions/new?type=choice&&id=${id}`)
      // const res = await choiceDetail({ id: id })
      // this.previewRowData = { ...res.data }
    },
    // 删除功能
    deleteList (id) {
      this.$confirm('是否删除该精选试题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove({ id: id })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          if (this.tableData.length === 0 && this.page !== 1) {
            this.page--
          }
          this.getQuestionsList()
        })
        .catch(() => {})
    },
    // 点击审核按钮
    check (id) {
      // this.$message({ message: '请输入审核意见', type: 'warning', customClass: 'messageIndex' })
      this.checkVisible = true
      this.checkId = id
    },
    // 关闭对话框
    // handleClose () {
    //   this.checkVisible = false
    // },
    // 审核意见提交
    // async handleSubmit () {
    //   await choiceCheck({
    //     id: this.checkId,
    //     ...this.formData
    //   })
    //   this.$message.success('审核成功')
    //   this.handleClose()
    //   this.getQuestionsList()
    // }

    // 点击搜索发送请求
    async searchListByCommand (obj) {
      const res = await choice({ ...obj, page: 1, pagesize: this.pagesize })
      console.log(res)
      this.tableData = res.data.items
      this.dataSet(this.tableData)
      this.total = res.data.counts
      this.activeName = 'all'
    },
    // 点击预览按钮
    async handlePreview (id) {
      this.showPreview = true
      const res = await choiceDetail({ id: id })
      // console.log(res, 'aaa')
      this.previewRowData = { ...res.data }
      console.log('123---', this.previewRowData)
      this.reduceTagQuestion = res.data.question.replace(/<[^>]+>/gi, '')
      this.reduceTagAnswer = res.data.answer.replace(/<[^>]+>/gi, '')
    },
    turnChoose (row) {
      if (Number(row.questionType) === 1) {
        return '单选'
      } else if (Number(row.questionType) === 2) {
        return '多选'
      } else {
        return '简答'
      }
    },
    difficultyFormatter (row) {
      const diff = +row.difficulty

      let x = ''
      switch (diff) {
        case 1:
          x = '简单'
          break
        case 2:
          x = '一般'
          break
        case 3:
          x = '困难'
          break
      }
      return x
    }
  }
  // async mounted () {
  //   const res = await choiceDetail({ id: id })
  //   this.previewRowData = { ...res.data }
  // }
}
</script>
<style lang="scss" >
 .messageIndex  {
    z-index:100000000 !important;
  }
</style>
<style lang="scss" scoped>
.pagination {
  margin: 10px 0 0 0;
  text-align: end;
}

</style>
